package com.sunline.gateway.handle;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunline.gateway.utils.AESUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class CustomGlobalExceptionHandler implements ErrorWebExceptionHandler {

    @Value("${AES.key}")
    private String key;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> errorResponse = new HashMap<>();
        if (ex.getMessage().contains(",")){
            errorResponse.put("message", ex.getMessage().split(",")[1]);
            errorResponse.put("errorCode", ex.getMessage().split(",")[0]);
        };
        errorResponse.put("result", null);
        errorResponse.put("success", "false");

        String errorJson = null;
        try {
            errorJson = new ObjectMapper().writeValueAsString(errorResponse);
            errorJson = AESUtil.encryptAES(errorJson,key);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(errorJson.getBytes());
        return exchange.getResponse().writeWith(Mono.just(dataBuffer));
    }
}
